package com.university.mentalhealthplatform.teacherV2.controller;

import com.university.mentalhealthplatform.appModels.Teacher;
import com.university.mentalhealthplatform.teacherV2.dto.TeacherDTO;
import com.university.mentalhealthplatform.teacherV2.service.TeacherServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v2/teachers")
@CrossOrigin(origins = "http://localhost:3000")
public class TeacherControllerV2 {

    @Autowired
    private TeacherServiceV2 teacherServiceV2;

    @GetMapping
    public ResponseEntity<List<Teacher>> getAllTeachers() {
        List<Teacher> teachers = teacherServiceV2.findAll();
        return ResponseEntity.ok(teachers);
    }

    @GetMapping("/me")
    public ResponseEntity<TeacherDTO> getCurrentTeacher(Authentication authentication) {
        String username = authentication.getName();
        Teacher teacher = teacherServiceV2.findByUsername(username);
        if (teacher == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(TeacherDTO.convertToDTO(teacher));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Teacher> getTeacherById(@PathVariable UUID id) {
        Teacher teacher = teacherServiceV2.getTeacherById(id);
        if (teacher == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(teacher);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Teacher> updateTeacher(@PathVariable UUID id, @RequestBody Teacher updatedTeacher) {
        Teacher teacher = teacherServiceV2.getTeacherById(id);
        if (teacher == null) {
            return ResponseEntity.notFound().build();
        }
        if (updatedTeacher.getPassword() == null) {
            updatedTeacher.setPassword(teacher.getPassword());
        }
        updatedTeacher.setId(id);
        Teacher savedTeacher = teacherServiceV2.saveTeacher(updatedTeacher);
        return ResponseEntity.ok(savedTeacher);
    }
}